﻿using System;
using System.Collections.Generic;
using SLNGP.Common.Extensions;
using SLNGP.Common.IoC;
using SLNGP.Core.Genes;
using SLNGP.Core.GeneticPrograms;
using SLNGP.Core.Run;

namespace SLNGP.Core.Individuals
{
    public class Individual : IIndividual
    {
        public Individual()
        {
        }

        public T ExecuteScalar<T>(params object[] variables)
        {
            var geneticProgrammingRun = IoC.Get<IGeneticProgrammingRun>();
            geneticProgrammingRun.InitializeVariablesFromUntypedListOfObjects(variables);
            return Chromosome.RootGene.Execute(geneticProgrammingRun).As<T>();
        }

        public object Fitness { get; set; }
        private IChromosome _chromosome;
        public IChromosome Chromosome
        {
            get
            {
                if (_chromosome == null)
                {
                    this.Chromosome = IoC.Get<IChromosome>();
                }
                return _chromosome;
            }
            set
            {
                _chromosome = value;
                _chromosome.ParentIndividual = this;
            }
        }

        public object SelectionMarker { get; set; }

        public bool IsValid
        {
            get { return Chromosome.IsValid; }
        }

        public void Fix()
        {
            Chromosome.Fix();
        }

        public IGeneticProgram ParentGeneticProgram { get; set; }

        public IEnumerable<IGene> AllGenes
        {
            get
            {
                return this.Chromosome.RootGene.SelectHierarchy(g => g.Children);
            }
        }

        public IIndividual CloneChild()
        {
            var ReturnValue = IoC.Get<IIndividual>();
            ReturnValue.ParentGeneticProgram = ParentGeneticProgram;
            ReturnValue.Chromosome = this.Chromosome.CloneChild(ReturnValue);
            return ReturnValue;
        }

        public string GetStringDisplay()
        {
            return Chromosome.GetStringDisplay();
        }

        public override string ToString()
        {
            return Chromosome.ToString();
        }
    }
}